package com.yuteng.video.service.impl;


import com.yuteng.video.entity.Search;
import com.yuteng.video.mapper.SearchRepository;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class SearchServiceImpl {
    @Autowired
    SearchRepository searchRepository;
    @Autowired
    ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    RedisTemplate redisTemplate;

    public Page<Search> like(String values, int pageNum, int pageSize) {
        List list = new ArrayList();
//          QueryBuilder queryBuilder=new TermQueryBuilder(msg+".keyword","*"+values+"*");
//          QueryBuilder queryBuilder2=new TermQueryBuilder("description"+".keyword","*"+values+"*");
        //    QueryBuilder queryBuilder = QueryBuilders.termQuery("type"+".keyword","娱乐");
//        特别注意的一点 wildcardQuery后面的参数，一定要是小写匹配，所以可以看到代码里使用了toLowerCase()；
//        而且使用的时候尽量避免*开头，这样能有效节省匹配时间
        //      QueryBuilder queryBuilder = QueryBuilders.wildcardQuery(msg+".keyword","*" + values + "*".toLowerCase());
        //    QueryBuilder queryBuilder1 = QueryBuilders.boolQuery().should(queryBuilder).should(queryBuilder2);
        QueryBuilder queryBuilder1 = QueryBuilders.wildcardQuery("title" + ".keyword", "*" + values + "*");
        QueryBuilder queryBuilder2 = QueryBuilders.wildcardQuery("description" + ".keyword", "*" + values + "*");
        QueryBuilder queryBuilder3 = QueryBuilders.boolQuery().should(queryBuilder1).should(queryBuilder2);
        //一定要注意-1！！！
        PageRequest request = PageRequest.of(pageNum-1, pageSize);
        Page<Search> search = searchRepository.search(queryBuilder3, request);

        return search;
    }

    public void saveSearch(Search search) {
        searchRepository.save(search);
    }

    public Page selectSearchByTitleOrDescription(String msg, int pageNum, int pageSize) {
//        QueryBuilder queryBuilder = QueryBuilders.wildcardQuery("title" + ".keyword", "*" + msg + "*".toLowerCase());
//        QueryBuilder queryBuilder1 = QueryBuilders.wildcardQuery("description" + ".keyword", "*" + msg + "*".toLowerCase());
//        QueryBuilder queryBuilder2 = QueryBuilders.boolQuery().should(queryBuilder).should(queryBuilder1);
//        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);
//        Page<Search> search = searchDao.search(queryBuilder2, pageRequest);
        return like(msg, pageNum, pageSize);

    }

    @Cacheable(cacheNames = "base_", key = "#pageNum")
    public Page getAll(int pageNum, int pageSize) {
        PageRequest pageRequest = PageRequest.of(pageNum - 1, pageSize);
        return searchRepository.findAll(pageRequest);
    }

    public List getLike(String name, int pageNum, int pageSize) {
        List<String> base = new ArrayList();
        List<String> list = new ArrayList();
        List<Search> last = new ArrayList();
        try {
            base.add("动画");//
            base.add("游戏");//
            base.add("电影");//
            base.add("综艺");//
            base.add("娱乐");//
            Map likeFromRedis = getLikeFromRedis(name);
            for (String m : base) {
                int o = (int) likeFromRedis.get(m);
                for (int ll = 0; ll < o; ll++) {
                    list.add(m);
                }
            }
            Random random = new Random();
            Set<Integer> set = new HashSet();
            /**
             * 只显示5个视频
             */
            for (int i = 0; i < 5; i++) {
                int j = random.nextInt(list.size());
                int size = set.size();
                set.add(j);
                while (size == set.size()) {
                    set.add(random.nextInt(list.size()));
                }
            }
            for (int x : set) {
                String s = list.get(x);
                System.out.println(s);
                QueryBuilder queryBuilder = QueryBuilders.wildcardQuery("type.keyword", "*" + s + "*".toLowerCase());
                List<Search> a = new ArrayList();
                Iterable<Search> search = searchRepository.search(queryBuilder);
                search.forEach(e -> a.add(e));
                Search next = null;
                if (a.isEmpty()) {
                    continue;
                } else {
                    next = a.get(0);
                    for (Search se : last) {
                        int num = 1;
                        while (next.getId().equals(se.getId())) {
                            if (a.size() < num) {
                                break;
                            }
                            next = a.get(num);
                            num++;
                        }
                    }
                }
                last.add(next);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            return last;
        }
    }

    @Cacheable(cacheNames = "like_", key = "#name")
    public Map getLikeFromRedis(String name) {
        //有数据库操作之后才存redis
        Map map = new HashMap();
        map.put("动画", 5);
        map.put("游戏", 5);
        map.put("综艺", 5);
        map.put("电影", 5);
        map.put("娱乐", 5);
//        redisTemplate.opsForValue().set("like_"+name,map);
//        redisTemplate.delete("like_"+name);
        return map;
    }
}
